package server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.*;

/**
 * @Authther: mrwu
 * @date:2021/3/30-03
 * @Description:server
 */
public class Connector {
    private int port =8080;

    private HashMap<String,HttpServlet> servletMap;

    public Connector(int port, HashMap<String, HttpServlet> servletMap) {
        this.port = port;
        this.servletMap = servletMap;
    }

    public void start(){
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Minicat 开始监听"+port);

            // 定义一个线程池
            int corePoolSize = 10;
            int maximumPoolSize =50;
            long keepAliveTime = 100L;
            TimeUnit unit = TimeUnit.SECONDS;
            BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
            ThreadFactory threadFactory = Executors.defaultThreadFactory();
            RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                    corePoolSize,
                    maximumPoolSize,
                    keepAliveTime,
                    unit,
                    workQueue,
                    threadFactory,
                    handler
            );

            while (true){
                Socket socket = serverSocket.accept();
                RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
                threadPoolExecutor.execute(requestProcessor);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
